const VERTEX_SHADER_SOURCE = `
  attribute vec4 a_Position;
  uniform vec4 u_Translation;
  void main() {
    gl_Position = a_Position + u_Translation;
  }
`;

const FRAGMENT_SHADER_SOURCE = `
  void main() {
    gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
  }
`;

let Tx = 0.5;
let Ty = 0.5;
let Tz = 0.0;
const main = () => {
  /** @type { WebGL2RenderingContext } */
  const gl = setupWebgl(document.querySelector("#root"));
  initShaders(gl, VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE);

  let n = initVertexBuffers(gl);
  if (n < 0) {
    console.error("Failed to set the positions of vertices.");
    return;
  }

  const aPosition = gl.getAttribLocation(gl.program, "a_Position");
  if (aPosition < 0) {
    console.error("Failed to get the storage location of a_Position");
    return;
  }

  const uTranslation = gl.getUniformLocation(gl.program, "u_Translation");
  if (!uTranslation) {
    console.error("Failed to get the storage location of u_Translation");
    return;
  }

  gl.uniform4f(uTranslation, Tx, Ty, Tz, 0.0);

  // 设置清空颜色
  gl.clearColor(0, 0, 0, 1);
  gl.clear(gl.COLOR_BUFFER_BIT);
  gl.drawArrays(gl.TRIANGLES, 0, n);
};

const initVertexBuffers = (gl) => {
  let vertices = new Float32Array([0.0, 0.5, -0.5, -0.5, 0.5, -0.5]);
  let n = 3;
  // 创建缓冲区对象
  let vertexBuffer = gl.createBuffer();

  if (!vertexBuffer) {
    console.error("Failed to create the buffer object.");
    return -1;
  }

  // 将缓冲区对象绑定到目标
  gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
  // 向缓冲区对象写入数据
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);

  // 获取 定点着色器中a_Position的引用或者指针
  const a_Position = gl.getAttribLocation(gl.program, "a_Position");
  // 讲当前缓冲区的数据分配给a_Position
  gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
  // 开启定点着色器访问缓冲区数据
  gl.enableVertexAttribArray(a_Position);
  return n;
};
